<template>
    <view class="bottom">
        <Header></Header>
        <view>
            <view class="back">
                <u-icon style="border: 1px #00eaff solid;border-radius: 50%;margin-left: 50rpx;margin-right: 20rpx"
                        name="arrow-left" color="#00eaff" @click="back"></u-icon>
                <text style="color: #00eaff;padding-right: 30rpx">Upgrade</text>
                <!--                <u-icon name="question-circle-fill" color="#00eaff" @click="toHelp"></u-icon>-->
            </view>
            <view>
                <u-popup ref="help" mode="center" width="95%" closeable :width="windowsWidth+'px'">
                    <view class="popup">
                        <view class="title">
                            <h3>玩法说明</h3>
                        </view>
                        <view class="content">
                            <view class="item">
                                <text>1、选择您想要的目标饰品</text>
                            </view>
                            <view class="item">
                                <text>2、选择好幸运饰品后，您可以通过滑动概率条来自由选择幸运概率，选择概率越大，获得目标幸运饰品的概率越大，概率区间为
                                    1%～80%，失败将获得封装的涂鸦
                                </text>
                            </view>
                            <view class="item">
                                <text>3、关于玩法：百分比的概率为每次独立事件，多次开启并不会累加</text>
                            </view>
                            <view class="item">
                                <text>
                                    4、关于概率：概率是在大样本(大量用户)下的统计数值，个体用户的少量数据之间存在一定差异。玩法存在概率性，请理性消费，切勿沉迷
                                </text>
                            </view>
                        </view>
                    </view>
                </u-popup>
            </view>
            <view class="prize-index">
                <view>
                    <view class="goods">
                        <view class="goods-item" v-if="!good.id" @click="selectGood">
                            <view style="height: 200rpx;display: flex;align-items: center;justify-content: center;">
                                <u-image src="@/static/images/prize-default.png" width="180rpx" height="135rpx"
                                         style="margin: 15rpx"></u-image>
                            </view>
                            <text>Choose accessories</text>
                        </view>
                        <view class="goods-item" v-else @click="selectGood">
                            <u-image :src="good.image" width="180rpx" height="135rpx" style="margin: 15rpx"></u-image>
                            <text>{{ good.goods_name }}</text>
                            <!--                        <text style="padding-top: 20rpx">-->
                            <!--                            <i class="custom-icon custom-icon-objects-color_diamond"-->
                            <!--                               style="padding-right:10rpx;color: #65a5c7"></i>-->
                            <!--                            {{ good.coin_price }}-->
                            <!--                        </text>-->
                        </view>

                        <view class="goods-item">
                            <!--                        <text>安慰奖</text>-->
                            <view style="height: 200rpx;display: flex;align-items: center;justify-content: center;">
                                <u-image src="@/static/images/prize-comfort.png" width="180rpx" height="135rpx"
                                         style="margin: 15rpx"></u-image>
                            </view>
                            <!--                        <text>{{ comfort_good.goods_name }}</text>-->
                            <text>Random Lucky Jewelry</text>
                            <!--                        <text style="padding-top: 20rpx">-->
                            <!--                            <i class="custom-icon custom-icon-objects-color_diamond"-->
                            <!--                               style="padding-right: 10rpx;color: #65a5c7"></i>-->
                            <!--                            {{ comfort_good.coin_price }}-->
                            <!--                        </text>-->
                        </view>

                    </view>
                </view>
                <view class="echarts">
                    <view class="echarts-img">
                    </view>
                    <view class="echarts-item" id="main"></view>

                </view>
                <!--                <view class="box_banner_switch">-->
                <!--                    <view class="box_banner_switch_item">-->
                <!--                        <u-switch v-model="skip" size="34" active-color="#19be6b"-->
                <!--                                  inactive-color="#ff9900"></u-switch>-->
                <!--                        <text>Skip animation</text>-->
                <!--                    </view>-->
                <!--                </view>-->


                <view class="slider">
                    <view class="slider-item">
                        <!--                    <view style="color: white">-->
                        <!--                        成功概率 :-->
                        <!--                        <text style="color: #2eec70">{{ sliderValue }}%</text>-->
                        <!--                        /-->
                        <!--                        失败概率：-->
                        <!--                        <text style="color: #ee4949">{{ 100 - sliderValue }}%</text>-->
                        <!--                    </view>-->
                        <slider v-model="sliderValue" activeColor="#98e184" backgroundColor="#2f3139"
                                @changing="sliderChanging" @change="sliderChanging" block-size="20"
                                block-color="#5d7ef2" min="1" max="80">
                            <view class="slider-item-value">
                                {{ sliderValue }}%
                            </view>
                        </slider>
                    </view>
                    <view class="button-item">
                        <u-button shape="circle" @click="createOrder" hover-class="none" :loading="loading"
                                  :custom-style="{backgroundColor: '#3a38b0',color: '#fff'}">
                            Try luck for
                            <i class="custom-icon custom-icon-objects-color_diamond"
                               style="padding-right: 10rpx;padding-left: 10rpx;color: #65a5c7"></i> {{ pay.toFixed(2) }}
                        </u-button>
                        <view style="padding-top: 20rpx">
                            <text>Set your winning chance between 1% to 80%</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="animation">
            <u-popup ref="animation" mode="center" :mask-close-able="false">
                <view>
                    <upgrade-animation :is-success="isSuccess" :amount="amount"
                                       :good="good" @close-animation="closeAnimation"></upgrade-animation>
                </view>
            </u-popup>
        </view>
        <view>
            <u-popup ref="prize" mode="center" border-radius="25" :mask-close-able="false" :width="windowsWidth+'px'">
                <view class="prize">
                    <view class="prizeInfo">
                        <view v-if="isSuccess">
                            <text>Congratulations on obtaining</text>
                        </view>
                        <view v-else>
                            <text>Unfortunately, you have obtained</text>
                        </view>
                        <view>
                            <u-image :src="prizeInfo.image" width="200rpx" height="200rpx"
                                     style="margin: 15rpx"></u-image>
                        </view>
                        <view>
                            <text>{{ prizeInfo.goods_name }}</text>
                        </view>
                    </view>
                    <view class="button">
                        <u-button type="primary" size="medium" @click="toPack">Put in your backpack</u-button>
                        <u-button type="success" size="medium" @click="toRecycle">
                            {{ prizeInfo.coin_price }}
                            <i class="custom-icon custom-icon-objects-color_diamond"
                               style="padding-left: 10rpx;color: #65a5c7"></i>
                            displace
                        </u-button>
                    </view>
                    <!--                    <view style="display: flex; justify-content: center">-->
                    <!--                        <u-button type="primary" @click="toPack">放入背包</u-button>-->
                    <!--                        <u-button type="success" @click="toRecycle">-->
                    <!--                            {{ prizeInfo.coin_price }}-->
                    <!--                            <i class="custom-icon custom-icon-objects-color_diamond"-->
                    <!--                               style="padding-left: 10rpx;color: #65a5c7"></i>-->
                    <!--                            回收-->
                    <!--                        </u-button>-->
                    <!--                    </view>-->
                </view>
            </u-popup>
        </view>
        <!-- 提示框 -->
        <u-toast ref="uToast"/>
        <custom-tabbar></custom-tabbar>
    </view>
</template>

<script>
import Header from "@/components/header/header.vue";
import CustomTabbar from "@/components/tabbar/tabbar.vue";
import * as echarts from 'echarts'
import UpgradeAnimation from "@/components/upgradeAnimation/upgradeAnimation.vue";

export default {
    name: 'prizeRate',
    components: {
        Header,
        CustomTabbar,
        UpgradeAnimation
    },
    data() {
        return {
            windowsWidth: 0,
            leftValue: 0,
            good: {},
            comfort_good: {
                id: '',
                goods_name: '',
                image: '',
                coin_price: ''
            },
            min: '',
            max: '',
            pay: 0.00,
            sliderValue: 1,
            myChart: null,
            loading: false,
            // 奖品
            prizeInfo: {},
            // 动画相关
            amount: 0,
            // 是否成功
            isSuccess: false,
            // 跳过动画
            skip: false
        };
    },
    // 接收参数
    onLoad(option) {
        if (option) {
            this.good.id = option.id;
            this.good.goods_name = option.goods_name;
            this.good.image = option.image;
            this.good.coin_price = option.coin_price;
        }
        this.getCustomBoxGoodsList();
    },
    onReady() {
        // 注意调用顺序，先初始化echarts才给echarts赋值
        this.initEcharts()
        this.setEchartsOption()
    },
    mounted() {
        this.windowsWidth = this.$store.getters.getWindowsWidth;
        document.documentElement.style.setProperty('--windows-width', this.windowsWidth + 'px');
        document.documentElement.style.setProperty('--windows-height', this.windowsWidth / 100 * 80 + 'px');
        let sliderHandle = document.querySelector('.uni-slider-handle');
        this.leftValue = window.getComputedStyle(sliderHandle).getPropertyValue('left');
        document.documentElement.style.setProperty('--left-value', this.leftValue);
    },
    methods: {
        // 返回
        back() {
            this.$u.route('/pages/index/index');
        },
        // 跳转帮助
        toHelp() {
            this.$refs.help.open()
        },
        // 选择头奖
        selectGood() {
            this.$u.route('/pages/prizeRate/customBox/customBox');
        },
        // 获取安慰奖商品
        getCustomBoxGoodsList() {
            this.$u.api.getCustomBoxGoodsList({
                comfort: 1,
            }).then(res => {
                this.comfort_good = res.data.data[0]
                if (this.good.id) {
                    this.getMinAndMaxAmount()
                }
            })
        },
        // 滑动
        sliderChanging(e) {
            this.sliderValue = e.detail.value;
            this.updateChart();
            this.pay = this.calculatedAmount(this.sliderValue);
            this.$nextTick(() => {
                let sliderHandle = document.querySelector('.uni-slider-handle');
                this.leftValue = window.getComputedStyle(sliderHandle).getPropertyValue('left');
                document.documentElement.style.setProperty('--left-value', this.leftValue);
            })
        },
        //获取最小金额和最大金额
        getMinAndMaxAmount() {
            this.$u.api.getPrizeRate({
                good_id: this.good.id,
                comfort_good_id: this.comfort_good.id
            }).then(res => {
                if (res.code === 1) {
                    this.min = res.data.min;
                    this.max = res.data.max;
                }
                this.pay = this.calculatedAmount(this.sliderValue);
            })
        },
        // 计算金额
        calculatedAmount(sliderValue) {
            if (!this.min || !this.max) {
                return 0
            }
            return this.min + (this.max - this.min) * (sliderValue - 1) / (80 - 1);
        },
        // 初始化echarts
        initEcharts() {
            let chartDom = document.getElementById('main');
            this.myChart = echarts.init(chartDom, '', {
                useDirtyRect: true
            });
        },
        // 配置echarts的option，展示数据图表
        setEchartsOption() {
            // ECharts配置项
            const option = {
                series: [{
                    type: 'gauge', // 图表类型：仪表盘
                    startAngle: 90, // 仪表盘起始角度
                    endAngle: -270, // 仪表盘结束角度
                    min: 0, // 最小刻度
                    max: 100, // 最大刻度
                    axisLine: { // 仪表盘轴线相关配置
                        lineStyle: {
                            type: 'dashed',
                            color: '#65a5c7',
                            width: 6 // 轴线宽度
                        }
                    },
                    // 进度条
                    progress: {
                        show: true,
                        width: 6,
                        itemStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: '#a811bd' // 0% 处的颜色
                                }, {
                                    offset: 1, color: '#ff8402' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            }
                        }
                    },
                    pointer: { // 指针相关配置
                        showAbove: false,
                        length: '80%',
                        icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
                        // width: 20,
                        // itemStyle: {
                        //     color: "rgba(255, 157, 0, 1)"
                        // }
                    },
                    axisTick: { // 刻度样式
                        show: true // 不显示刻度
                    },
                    splitLine: { // 分隔线样式
                        show: false,
                    },
                    axisLabel: { // 刻度标签样式
                        show: false,
                    },
                    anchor: { // 锚点样式
                        show: false, // 显示锚点
                    },
                    title: { // 仪表盘标题样式
                        show: false // 不显示标题
                    },
                    detail: { // 仪表盘详情，即指针下方的数值显示
                        valueAnimation: true, // 是否开启数值动画
                        offsetCenter: [0, 0],
                        formatter: '{value}%', // 数值格式化
                        color: '#fff', // 数值颜色，这里设置为自动
                        // backgroundColor: '#000',
                        width: '100%',
                        height: '100%',
                        // borderRadius: [130, 130, 130, 130]
                    },
                    data: [{ // 仪表盘数据
                        value: this.sliderValue // 初始值与Slider组件的值一致
                    }]
                }]
            };

            // 应用配置项
            this.myChart.setOption(option);
        },
        // 更新图表
        updateChart() {
            const option = {
                series: [{
                    data: [{
                        value: this.sliderValue
                    }]
                }]
            };
            this.myChart.setOption(option);
        },
        // 创建订单
        createOrder() {
            this.loading = true;
            this.$nextTick(() => {
                if (!this.good.id) {
                    this.$refs.uToast.show({
                        title: 'Please select accessories first',
                        type: 'error',
                    })
                    return
                }
                this.$u.api.createCustomBoxOrder({
                    good_id: this.good.id,
                    comfort_good_id: this.comfort_good.id,
                    pay: this.pay
                }).then(res => {
                    if (res.code === 1) {
                        // 创建订单支付
                        this.$u.api.customBoxCoinPay({
                            order_id: res.data.order_id
                        }).then(response => {
                            if (response.code === 1) {
                                this.$u.api.getUserInfo().then(ress => {
                                    if (ress.code === 1) {
                                        const user = ress.data;
                                        // 提交mutation来更新Vuex中的状态
                                        this.$store.commit('user/SET_USER', user);
                                        // 保存到本地存储
                                        uni.setStorageSync('user', user);
                                    }
                                })
                                this.prizeInfo = response.data.prize.prizeInfo[0];
                                if (!this.skip) {

                                    setTimeout(() => {
                                        if (this.prizeInfo.good_id == this.good.id) {
                                            this.isSuccess = true;
                                            this.amount = 100;
                                        } else {
                                            this.amount = this.getRandomQuadrant(this.sliderValue);
                                        }
                                        this.$refs.animation.open();
                                    }, 200)

                                } else {
                                    setTimeout(() => {
                                        this.$refs.prize.open();
                                    }, 500);
                                }
                            } else {
                                this.$refs.uToast.show({
                                    title: response.msg,
                                    type: 'error',
                                })
                            }
                        })
                    } else {
                        this.$refs.uToast.show({
                            title: res.msg,
                            type: 'error',
                        })
                    }
                })
            })
            this.loading = false;
        },
        getRandomQuadrant(sliderValue) {
            // 确保sliderValue在1-80之间
            sliderValue = Math.min(80, Math.max(1, sliderValue));

            // 将sliderValue映射到0-1的范围
            const mappedSliderValue = (sliderValue - 1) / 79;

            // 计算第一象限的概率
            const firstQuadrantChance = 1 - mappedSliderValue;

            // 生成一个0-1之间的随机数
            const randomNum = Math.random();

            // 根据随机数和概率确定象限
            if (randomNum < firstQuadrantChance) {
                return 25;
            } else if (randomNum < firstQuadrantChance + 0.25) {
                return 50;
            } else if (randomNum < firstQuadrantChance + 0.25 + 0.25) {
                return 75;
            } else {
                return 100;
            }
        },
        // 关闭动画
        closeAnimation() {
            this.$refs.animation.close();
            this.$refs.prize.open();
        },
        // 放入背包
        toPack() {
            this.$refs.prize.close();
        },
        // 回收
        toRecycle() {
            this.$u.api.exchange({
                record_ids: this.prizeInfo.prize_id
            }).then(res => {
                if (res.code === 1) {
                    this.$refs.uToast.show({
                        title: res.msg,
                        type: 'success'
                    });
                    this.$u.api.getUserInfo().then(response => {
                        if (response.code === 1) {
                            const user = response.data;
                            // 提交mutation来更新Vuex中的状态
                            this.$store.commit('user/SET_USER', user);
                            // 保存到本地存储
                            uni.setStorageSync('user', user);
                        }
                    })
                } else {
                    this.$refs.uToast.show({
                        title: res.msg,
                        type: 'error'
                    });
                }
            })
            this.$refs.prize.close();
        }

    },

}
</script>

<style lang="scss" scoped>
.back {
    line-height: 100rpx;
    //margin-left: 30rpx;
    color: white;
    font-size: 34rpx;
    background-image: url("@/static/images/header-bg.png");
    background-size: cover;
    height: 100rpx;
}

.popup {
    background-color: #0f0e2d;

    .title {
        text-align: center;
        padding: 20rpx;
    }

    .content {
        .item {
            padding: 20rpx;
        }
    }
}

@keyframes rotateBackground {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.echarts {
    //background-color: #251c49;
    //background-image: url("@/static/images/prize-bg.png");
    //background-size: 100% 100%;
    //background-repeat: no-repeat;
    //background-position: center;

    position: relative;
    //display: flex;
    //justify-content: center;
    //align-items: center;
    width: var(--windows-width);
    height: var(--windows-width);

    .echarts-img {
        position: absolute;
        //top: 50%;
        //left: 50%;
        transform: (translate(-50%, -50%));
        width: var(--windows-width);
        height: var(--windows-width);
        //background-image: url("@/static/images/prize-item.png");
        background-image: url("@/static/images/prize-bg.png");
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: center;
        animation: rotateBackground 10s linear infinite;


    }

    .echarts-item {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: (translate(-50%, -50%));
        padding: 30rpx;
        //left: 20rpx;
        width: 350rpx;
        height: 350rpx;

    }


}

.box_banner_switch {
    display: flex;
    flex-direction: row-reverse;
    padding-top: 20rpx;


    .box_banner_switch_item {
        display: flex;
        align-items: center;
        color: white;
    }
}

.prize-index {
    background-image: url("@/static/images/prize-index-bg.png");
    background-size: var(--windows-width) 50%;
    background-repeat: no-repeat;
    background-position: center;
}

.goods {
    padding-top: 30rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
    align-items: center;

    .goods-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        width: 300rpx;
        height: 250rpx;
        //background-color: #3f536e;
        background-image: url("@/static/images/prizeRate-bg.png");
        background-size: 100% 100%;
        border-radius: 50rpx;
        color: white;
    }
}

.slider {
    display: flex;
    flex-direction: column;
    align-items: center;

    .slider-item {
        width: 100%;
        //background-color: #162c66;
        padding: 20rpx;
        border-bottom-left-radius: 20rpx;
        border-bottom-right-radius: 20rpx;
        position: relative;
        //display: flex;
        //flex-direction: column;
        //text-align: center;

        .slider-item-value {
            color: #00eaff;
            position: absolute;
            padding-left: 35rpx;
            width: 20rpx;
            margin: 0;
            top: 5rpx;
            left: var(--left-value);
        }
    }

    .button-item {
        width: 80%;
        padding: 20rpx;
        text-align: center;
    }
}

.animation {
    ::v-deep.u-mode-center-box {
        //width: var(--windows-width);
        //height: 100%;
        background-color: transparent
    }
}

.prize {
    padding: 30rpx;
    background-color: #0f0e2d;

    .prizeInfo {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin: 20rpx;
    }

    .button {
        display: flex;

        ::v-deep .u-size-medium {
            display: flex;
            width: 40%;
        }
    }
}

::v-deep .u-type-success {
    background-color: #0f0e2d;
    border: none;
}

::v-deep .u-type-error {
    background-color: #0f0e2d;
    border: none;
}
</style>
